package tcp;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Collections;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;

public class ConnectionListener implements Runnable, NewConnectionSubject
{
	private volatile boolean            isRunning;
	private ServerSocket                serverSocket; 
	private Thread                      listenerThread;
	private List<NewConnectionObserver> observers;
	private int                         listenPort;
	
	public ConnectionListener(int listenPort)
	{
		observers =
			 Collections.synchronizedList(new LinkedList<NewConnectionObserver>());
		
		this.listenPort = listenPort;
	}
	
	public void addNewConnectionObserver(NewConnectionObserver o)
	{
		observers.add(o);
	}
	
	public void notifyObservers(Socket s)
	{
		for(NewConnectionObserver observer : observers) 
			observer.handleNewConnection(s);
	}
	
	public void removeNewConnectionObserver(NewConnectionObserver o)
	{
		observers.remove(o);
	}
	
	public void run()
	{
		try {
			serverSocket = new ServerSocket(listenPort); 
			System.out.println("Listening on port " + listenPort + "...");
			
			
			
		} catch (IOException ioe) {
				ioe.printStackTrace(); 
		} 
		
		while(isRunning)
		{
			try {
				Socket s = serverSocket.accept(); 
				System.out.println("Connection accepted...");
				this.notifyObservers(s);
				
			} catch(IOException ioe) {
				ioe.printStackTrace();
			}
		} 
	}
	
	public void start()
	{
		if(listenerThread == null)
		{
			System.out.println("Starting listener thread...");
			isRunning = true;
			listenerThread = new Thread(this);
			listenerThread.start();
		}
	}
}